<template>
    <div ref="topDiv">
        <Split v-model="split1" style="height: 100%; " class="demo-split">
            <div slot="left" style="height: 100%; overflow-y: auto; overflow-x: hidden; padding: 5px">
                <Row :gutter="16">
                    <i-col span="24">
                        <Input v-model="value" placeholder="请输入环保画像标准..." style="width: 100%" suffix="ios-search" @on-enter='searchTree(value, standardTree)' clearable @on-clear="clearTree"/>
                    </i-col>
                </Row>
                <Tree ref="tree" :data="standardTree"  :load-data="handleLoadData" :render="renderContent" style="width: 100%" @on-contextmenu="handleContextMenu">
                    <template slot="contextMenu">
                        <DropdownItem @click.native="toAddStandard" v-if="ifAddButton">添加画像标准</DropdownItem>
                        <DropdownItem @click.native="toImportStandard" v-if="ifImportButton">导入画像标准</DropdownItem>
                        <DropdownItem @click.native="toUpdateStandard" v-if="ifUpdateButton">修改画像标准</DropdownItem>
                        <DropdownItem @click.native="deleteStandard" v-if="ifDeleteButton" style="color: #ed4014">删除画像标准</DropdownItem>
                    </template>
                </Tree>
            </div>
            <div slot="right" class="demo-split-pane">
                <Row class="query-form">
                    <i-col span="24">
                        <Button size="large" type="success" class="ivu-btn-add" icon="md-add" @click="addInfo" v-if="ifAddDetail">新增
                        </Button>
                    </i-col>
                </Row>
                <Table ref='table' :loading="loading" border :columns="columns" no-data-text="请选择环保画像标准"
                       :data="infos" width="100%" :height="tableHeight2"  highlight-row stripe size="small"></Table>
                <Row type="flex" justify="end" >
                    <i-col>
                        <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                              @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
                    </i-col>
                </Row>
            </div>
        </Split>
        <Modal :title="modalTitle" :transfer=false v-model="modal1" :width=800>
            <Form :model="formItem" ref="formCustom"  label-position="top" :rules="ruleCustom">
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="12">
                        <FormItem label="管理要素：" prop="managementElements">
                            <Select v-model="formItem.managementElements" filterable>
                                <Option v-for="item in codingList1" :value="item.codingCodeId">{{item.codingName}}</Option>
                            </Select>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="控制因子：" prop="pollutionFactor">
                            <Select v-model="formItem.pollutionFactor" filterable>
                                <Option v-for="item in codingList2" :value="item.codingCodeId">{{item.codingName}}</Option>
                            </Select>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="24">
                        <FormItem label="法律责任：" prop="legalResponsibility">
                            <Input v-model="formItem.legalResponsibility" maxlength="2000" show-word-limit type="textarea" placeholder="请输入法律责任..." style="width: 100%" />
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="12">
                        <FormItem label="法律法规依据：" prop="lawsRegulations">
                            <Input v-model="formItem.lawsRegulations" maxlength="500"  show-word-limit></Input>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="风险等级：" prop="riskLevel">
                            <Select v-model="formItem.riskLevel" filterable>
                                <Option v-for="item in codingList3" :value="item.codingCodeId">{{item.codingName}}</Option>
                            </Select>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="saveDetail()">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="modal1=false" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
        <Modal :title="modalTitle" :transfer=false v-model="modal2" :width=800>
            <Form :model="formInfo" ref="infoCustom"  label-position="top" :rules="ruleCustom">
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="24">
                        <FormItem label="画像标准：" prop="title">
                            <Input v-model="formInfo.title" maxlength="255"  show-word-limit></Input>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="24">
                        <FormItem label="所属二级集团：" prop="orgId">
                            <Select v-model="formInfo.orgId" filterable>
                                <Option v-for="item in twoLevelOrgList" :value="item.orgId" :key="item.orgId">{{ item.orgName }}</Option>
                            </Select>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="saveInfo()">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="modal2=false" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
        <Modal :title="modalTitle" :transfer=false v-model="modal3" :width=800>
            <Form :model="formSubitem" ref="subitemCustom"  label-position="top" :rules="ruleCustom">
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="24">
                        <FormItem label="上级目录：" prop="parentName">
                            <Input v-model="formSubitem.parentName" show-word-limit style="width: 100%" readonly/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="24">
                        <FormItem label="标题：" prop="title">
                            <Input v-model="formSubitem.title" maxlength="2000" show-word-limit type="textarea" placeholder="请输入标题..." style="width: 100%" />
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="saveSubitem()">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="modal3=false" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
        <Modal title="画像标准管理" :transfer=false v-model="modal4" :width=800>
            <Form :model="formItem" :label-width="120" >
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="11">
                        <FormItem label="管理要素：">
                            {{formItem.managementElementsName}}
                        </FormItem>
                    </i-col>
                    <i-col span="11">
                        <FormItem label="控制因子：" >
                            {{formItem.pollutionFactorName}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="24">
                        <FormItem label="法律责任：">
                            {{formItem.legalResponsibility}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <i-col span="11">
                        <FormItem label="法律法规依据：">
                            {{formItem.lawsRegulations}}
                        </FormItem>
                    </i-col>
                    <i-col span="11">
                        <FormItem label="风险等级：" >
                            {{formItem.riskLevelName}}
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="modal4=false">关闭</Button>
            </div>
        </Modal>


        <Modal title="画像标准管理" :transfer=false v-model="showFileImportModal" :width=1200>
            <Form :model="formItem" :label-width="120" >
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="24">
                        <Upload action=""
                                :format="['xlsx']"
                                :before-upload="importFileByTemplate">
                            <Button class="ivu-btn-query" icon="ios-cloud-upload-outline">上传导入文件</Button>
                        </Upload>
                    </Col>
                </Row>
                <Row>
                    <Col span="24">
                        <Spin style="margin-top:20px;margin-left:48%;height:440px" v-if="loading"></Spin>
                        <Tabs style="margin-top:20px;height:440px" v-else v-model="currentSheet">
                            <TabPane v-for="(item,index) in sheetInfos" :label="item.sheetName" :name="item.sheetName">
                                <Table height="400" no-data-text="没有查询到相关数据!"  size="small"  :span-method="handleSpan"
                                       highlight-row stripe border :columns="columns2" width="100%" :data="item.standardDataByTemplate">
                                </Table>
                            </TabPane>
                        </Tabs>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' style="margin-left:20px" @click="showFileImportModal=false">关闭</Button>
                <Button class='ivu-btn-save'  @click="saveStandardInfoByTemplate" :loading="buttonLoading">保存</Button>
            </div>
        </Modal>
    </div>
</template>

<script>

    import {sessionStorage} from '@/common/cacheUtils.js';
    let cascaderDom = () => import('@/components/cascader-dom.vue');;
    import {Api} from '../../../api/index.js'

    export default {
        name: "standard",
        data(){
            return {
                standardDatasByTemplate:{},
                currentSheet:"",
                sheetInfos:[],
                ifAddDetail:false,
                ifAddButton: true,
                ifImportButton:false,
                ifUpdateButton: true,
                ifDeleteButton: true,
                buttonLoading: false,
                modalTitle: '',
                modal1: false,
                modal2: false,
                modal3: false,
                modal4: false,
                loading: false,
                split1: 0.25,
                value: '',
                showFileImportModal:false,
                managementElementsMap:{},
                pollutionFactorMap:{},
                managementElementsIdMap:{},
                pollutionFactorIdMap:{},
                riskLevelMap:{},
                riskLevelIdMap:{},
                standardTree: [{
                    title: '画像标准管理',
                    loading: false,
                    contextmenu: true,
                    children: [],
                    type: 0
                }],
                columns: [
                    {
                        type: 'index.js',
                        title: '编号',
                        width: 75,
                        align: 'center',
                    },
                    {
                      title:'是否可用',
                      width: 95,
                      align:'center',
                        render: (h, params) => {
                            let flag =(this.userInfo.companyId == params.row.orgId)
                            return h(
                                'i-Switch',
                                {
                                    props: {
                                        size: 'large',
                                        value: params.row.enabled == "1"
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: flag ? '':'#d0d0d0',
                                        pointerEvents: flag?'':'none'
                                    },
                                    scopedSlots: {
                                        open: () => h('span', "可用"),
                                        close: () => h('span', "不可用")
                                    },
                                    on: {
                                        'on-change': (e) => {
                                            let data = {
                                                detailId:params.row.detailId,
                                                enabled : e == true?"1":"0"
                                            }
                                            this.$http.put(Api.updateEcoPortraitStandardDetail,data).then(function(res) {
                                            })
                                        }
                                    }
                                }
                            )
                        }
                    },
                    {
                        title: '管理要素',
                        align: 'center',
                        key: 'managementElements',
                        minWidth: 90,
                        render:(h,params)=>{
                            let value = '';
                            value = this.managementElementsIdMap[params.row.managementElements]
                            return h('div',[
                                h('span',value || '--')
                            ]);
                        }
                    },
                    {
                        title: '控制因子',
                        align: 'center',
                        key: 'pollutionFactor',
                        minWidth: 100,
                        render:(h,params)=>{
                            let value = '';
                            value = this.pollutionFactorIdMap[params.row.pollutionFactor]
                            return h('div',[
                                h('span',value || '--')
                            ]);
                        }
                    },
                    {
                        title: '法律责任',
                        align: 'center',
                        key: 'legalResponsibility',
                        tooltip: true,
                        minWidth: 90,
                    },
                    {
                        title: '法律法规依据',
                        align: 'center',
                        key: 'lawsRegulations',
                        tooltip: true,
                        minWidth: 120
                    },
                    {
                        title: '风险等级',
                        align: 'center',
                        key: 'riskLevel',
                        minWidth: 80,
                        render:(h,params)=>{
                            let value = '';
                            value = this.riskLevelIdMap[params.row.riskLevel]
                            return h('div',[
                                h('span',value || '--')
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        minWidth: 150,
                        render: (h, params) => {
                            let flag =(this.userInfo.companyId == params.row.orgId)
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.formItem = params.row;
                                            this.codingList1.forEach(i =>{
                                                if(i.codingCodeId == this.formItem.managementElements) this.formItem.managementElementsName = i.codingName;
                                            })
                                            this.codingList2.forEach(i =>{
                                                if(i.codingCodeId == this.formItem.pollutionFactor) this.formItem.pollutionFactorName = i.codingName;
                                            })
                                            this.codingList3.forEach(i =>{
                                                if(i.codingCodeId == this.formItem.riskLevel) this.formItem.riskLevelName = i.codingName;
                                            })
                                            this.modal4 = true;
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: flag ? '':'#d0d0d0',
                                        pointerEvents: flag?'':'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.isUpdate = true;
                                            this.formItem = params.row;
                                            this.modal1 = true;
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: flag ? 'red':'#d0d0d0',
                                        pointerEvents: flag?'':'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteDetail(params.row);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                columns2: [
                    {
                        type: 'index.js',
                        title: '序号',
                        width: 100,
                        align: 'center',
                    },
                    {
                        minWidth: 120,
                        title: '管理要素',
                        align: 'center',
                        key:'managementElementsName'
                    },
                    {
                        minWidth: 120,
                        title: '控制因子',
                        align: 'center',
                        key:'pollutionFactorName'
                    },
                    {
                        minWidth: 200,
                        title: '法律责任',
                        align: 'center',
                        key:'legalResponsibility'
                    },
                    {
                        minWidth: 200,
                        title: '法律法规依据',
                        align: 'center',
                        key:'lawsRegulations'
                    },
                    {
                        width: 100,
                        title: '风险等级',
                        align: 'center',
                        key:'riskLevelName'
                    },
                ],
                infos: [],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                pageSizeArray: [10, 20, 50],
                tableHeight2: '',
                codingList1: [],
                codingList2: [],
                codingList3: [],
                formItem: {},
                ruleCustom: {
                    managementElements: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    pollutionFactor: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    legalResponsibility: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    lawsRegulations: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    riskLevel: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    title: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                    orgId: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur, change'
                    }],
                },
                selectNodeInfo: {},
                isUpdate: false,
                userInfo: sessionStorage('userId').getObject('userId'),
                contextData: {},
                formInfo: {},
                twoLevelOrgList: [],
                formSubitem: {}
            }
        },
        watch: {
            "modal1": function (qw,er) {
                if(!qw){
                    this.formItem = {};
                }
            },
            "modal2": function (qw,er) {
                if(!qw){
                    this.formInfo = {};
                }
            }
        },
        mounted(){
            this.$refs.topDiv.style.height = (window.innerHeight - 120) + 'px';
            this.tableHeight2 = window.innerHeight - 200;
            this.loadStandard(this.standardTree[0]);
            this.queryCodingSort();
        },
        methods: {
            query() {
                this.loading = true;
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    conditions: {subitemId: this.selectNodeInfo.id}
                };
                this.$http.get(Api.queryEcoPortraitStandardDetail, {
                    params: data
                }).then(function (res) {
                    this.infos = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }, function (res) {
                    this.$Message.error('请求失败');
                });
            },
            loadStandard(parent) {
                let data = {orgId: this.userInfo.companyId}
                this.$http.get(Api.queryEcoPortraitStandard, {params: data}).then(res => {
                    parent.children = [];
                    res.data.data.forEach(i => {
                        let obj = {
                            title: i.title,
                            id: i.standardId,
                            orgId: i.orgId,
                            loading: false,
                            contextmenu: true,
                            children: [],
                            type: 1
                        }
                        parent.children.push(obj);
                        this.$set(parent, 'expand', true);
                    })
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            handleLoadData(item, callback) {
                this.$http.get(Api.queryEcoPortraitStandardSubitem, {params: {parentId: item.id}}).then(res => {
                    let children = [];
                    res.data.data.forEach(i => {
                        let obj = {
                            parentId: i.parentId,
                            orgId: i.orgId,
                            title: i.title,
                            id: i.subitemId,
                            parentName: item.title,
                            contextmenu: true,
                            type: 2
                        }
                        children.push(obj);
                    })
                    callback(children);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            renderContent(h, {root, node, data}) {
                let icon = "ios-folder";
                if (data.type == 2) {
                    icon = "ios-document";
                }
                return h('span', {
                        style: {
                            display: 'inline-block',
                            cursor: "pointer",
                            color: node.node.selected ? "#2d8cf0" : "black" //根据选中状态设置样式
                        },
                        on: {
                            click: () => {
                                this.ifAddDetail = true;
                                this.selectNodeInfo = data;
                                if (data.type == 2) {
                                    this.query();
                                }
                                if (data.type == 2 && ((data.orgId == this.userInfo.companyId && this.selectNodeInfo.title != '其他')
                                    || this.userInfo.twoLevelOrgId == data.orgId && this.selectNodeInfo.title == '其他')) {
                                    this.ifAddDetail = true;
                                    this.tableHeight2 = window.innerHeight - 240;
                                } else {
                                    this.ifAddDetail = false;
                                    this.tableHeight2 = window.innerHeight - 200;
                                }
                            }
                        }
                    },
                    [
                        h('span', [
                            h('Icon', {
                                props: {
                                    type: icon,
                                },
                                style: {
                                    marginRight: '5px',
                                    color: '#FF7F00'
                                }
                            }),
                            h('span', data.title)
                        ])
                    ]
                );
            },
            searchTree(value, arr) {
                let children = arr[0].children;
                let newarr = [];
                children.forEach(element => {
                    if (element.title.indexOf(value) > -1) {
                        newarr.push(element);
                    }
                });
                this.standardTree[0].children = newarr;
            },
            clearTree() {
                let data = {}
                this.$http.get(Api.queryEcoPortraitStandard, {params: data}).then(res => {
                    this.standardTree[0].children = [];
                    res.data.data.forEach(i => {
                        let obj = {
                            title: i.title,
                            id: i.standardId,
                            orgId: i.orgId,
                            loading: false,
                            contextmenu: true,
                            children: [],
                            type: 1
                        }
                        this.standardTree[0].children.push(obj);
                        this.$set(this.standardTree[0], 'expand', true);
                    })
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            queryCodingSort() {
                this.$http.get(Api.queryCodeDetailBySortId + '/eco-00001', {params: {}}).then((res) => {
                    this.codingList1 = res.data.data;
                    this.codingList1.forEach(item=>{
                        this.managementElementsMap[item.codingName] = item.codingCodeId;
                        this.managementElementsIdMap[item.codingCodeId] = item.codingName;
                    })
                });
                this.$http.get(Api.queryCodeDetailBySortId + '/eco-00002', {params: {}}).then((res) => {
                    this.codingList2 = res.data.data;
                    this.codingList2.forEach(item=>{
                        this.pollutionFactorMap[item.codingName] = item.codingCodeId;
                        this.pollutionFactorIdMap[item.codingCodeId] = item.codingName;
                    })
                });
                this.$http.get(Api.queryCodeDetailBySortId + '/eco-00003', {params: {}}).then((res) => {
                    this.codingList3 = res.data.data;
                    this.codingList3.forEach(item=>{
                        this.riskLevelMap[item.codingName] = item.codingCodeId;
                        this.riskLevelIdMap[item.codingCodeId] = item.codingName;
                    })
                });
                this.$http.get(Api.twoPlusFourReceipt + '/twoLevelOrg').then((res) => {
                    if (res.data.status == 200) {
                        this.twoLevelOrgList = res.data.data;
                    }
                })
            },
            addInfo() {
                this.modalTitle = '新增';
                this.modal1 = true;
                this.isUpdate = false;
            },
            saveDetail() {
                this.$refs['formCustom'].validate((valid) => {
                    if (valid) {
                        this.formItem.subitemId = this.selectNodeInfo.id;
                        this.formItem.createUserId = this.userInfo.userId;
                        this.formItem.updateUserId = this.userInfo.userId;
                        if (this.isUpdate) {
                            this.$http.put(Api.updateEcoPortraitStandardDetail, this.formItem).then(function (response) {
                                this.buttonLoading = false;
                                this.modal1 = false;
                                this.query();
                                this.$Message.success({content: '保存成功', duration: 4});
                            });
                        } else {
                            if (this.userInfo.twoLevelOrgId == this.userInfo.companyId) {
                                this.formItem.enabled = "1";
                            } else {
                                this.formItem.enabled = "0";
                            }
                            this.$http.post(Api.saveEcoPortraitStandardDetail, this.formItem).then(function (response) {
                                this.buttonLoading = false;
                                this.modal1 = false;
                                this.query();
                                this.$Message.success({content: '保存成功', duration: 4});
                            });
                        }
                    }
                });
            },
            handleContextMenu(data) {
                this.contextData = data;
                if (this.userInfo.twoLevelOrgId != this.userInfo.companyId && this.userInfo.companyId != '18000000') {
                    this.ifAddButton = false;
                    this.ifImportButton = true;
                    this.ifUpdateButton = false;
                    this.ifDeleteButton = false;
                } else if (this.contextData.type == 0) {
                    this.ifImportButton = true;
                    this.ifAddButton = true;
                    this.ifUpdateButton = false;
                    this.ifDeleteButton = false;
                } else if (this.contextData.type == 1) {
                    this.ifImportButton = false;
                    this.ifAddButton = true;
                    this.ifUpdateButton = true;
                    this.ifDeleteButton = true;
                } else if (this.contextData.type == 2) {
                    this.ifImportButton = false;
                    this.ifAddButton = false;
                    this.ifUpdateButton = true;
                    this.ifDeleteButton = true;
                }
            },
            deleteDetail(row) {
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该条信息</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.deleteEcoPortraitStandardDetail, {
                            params: {
                                detailId: row.detailId,
                                updateUserId: this.userInfo.userId,
                            }
                        }).then((res) => {
                            this.$Message.success({content: '删除成功', duration: 4});
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            toAddStandard() {
                if (this.contextData.type == 0) {
                    this.modalTitle = '画像标准新增';
                    this.modal2 = true;
                    this.isUpdate = false;
                } else {
                    this.modalTitle = '画像标准子项新增';
                    this.modal3 = true;
                    this.isUpdate = false;
                    this.formSubitem = {
                        parentId: this.contextData.id,
                        parentName: this.contextData.title
                    };
                }
            },
            saveInfo() {
                this.$refs['infoCustom'].validate((valid) => {
                    if (valid) {
                        this.formInfo.createUserId = this.userInfo.userId;
                        this.formInfo.updateUserId = this.userInfo.userId;
                        if (this.isUpdate) {
                            this.$http.put(Api.updateEcoPortraitStandard, this.formInfo).then(function (response) {
                                this.buttonLoading = false;
                                this.modal2 = false;
                                this.loadStandard(this.standardTree[0]);
                                this.$Message.success({content: '保存成功', duration: 4});
                            });
                        } else {
                            this.$http.post(Api.saveEcoPortraitStandard, this.formInfo).then(function (response) {
                                this.buttonLoading = false;
                                this.modal2 = false;
                                this.loadStandard(this.standardTree[0]);
                                this.$Message.success({content: '保存成功', duration: 4});
                            });
                        }
                    }
                });
            },
            deleteStandard() {
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该条信息</p>',
                    okText: '确认',
                    onOk: () => {
                        if (this.contextData.type == 1) {
                            this.$http.delete(Api.deleteEcoPortraitStandard, {
                                params: {
                                    standardId: this.contextData.id,
                                    updateUserId: this.userInfo.userId,
                                }
                            }).then((res) => {
                                this.loadStandard(this.standardTree[0]);
                                this.$Message.success({content: '删除成功', duration: 4});
                                this.query();
                            });
                        } else {
                            this.$http.delete(Api.deleteEcoPortraitStandardSubitem, {
                                params: {
                                    subitemId: this.contextData.id,
                                    updateUserId: this.userInfo.userId,
                                }
                            }).then((res) => {
                                this.loadStandard(this.standardTree[0]);
                                this.$Message.success({content: '删除成功', duration: 4});
                                this.query();
                            });
                        }
                    },
                    cancelText: '取消'
                });
            },
            toUpdateStandard() {
                if (this.contextData.type == 1) {
                    this.modalTitle = '画像标准修改';
                    this.formInfo = {
                        standardId: this.contextData.id,
                        title: this.contextData.title,
                        orgId: this.contextData.orgId,
                    };
                    this.isUpdate = true;
                    this.modal2 = true;
                } else if (this.contextData.type == 2) {
                    this.modalTitle = '画像标准子项修改';
                    this.formSubitem = {
                        subitemId: this.contextData.id,
                        title: this.contextData.title,
                        parentId: this.contextData.parentId,
                        parentName: this.contextData.parentName
                    };
                    this.isUpdate = true;
                    this.modal3 = true;
                }
            },
            saveSubitem() {
                this.$refs['subitemCustom'].validate((valid) => {
                    if (valid) {
                        this.formSubitem.createUserId = this.userInfo.userId;
                        this.formSubitem.updateUserId = this.userInfo.userId;
                        if (this.isUpdate) {
                            this.$http.put(Api.updateEcoPortraitStandardSubitem, this.formSubitem).then(function (response) {
                                this.buttonLoading = false;
                                this.modal3 = false;
                                this.loadStandard(this.standardTree[0]);
                                this.$Message.success({content: '保存成功', duration: 4});
                            });
                        } else {
                            this.$http.post(Api.saveEcoPortraitStandardSubitem, this.formSubitem).then(function (response) {
                                this.buttonLoading = false;
                                this.modal3 = false;
                                this.loadStandard(this.standardTree[0]);
                                this.$Message.success({content: '保存成功', duration: 4});
                            });
                        }
                    }
                });
            },
            saveStandardInfoByTemplate(){
              this.buttonLoading = true;
                this.$http.post(Api.saveStandardByTemplate, this.standardDatasByTemplate).then(function (res) {
                    if(res.data.status == 200) {
                        this.buttonLoading = false;
                        this.showFileImportModal = false;
                        this.$Message.success({content: '保存成功', duration: 4});
                    }else{
                        this.$Message.success({content: res.data.msg, duration: 4});
                    }
                });
            },
            handleSpan ({ row, column, rowIndex, columnIndex }) {
                if (columnIndex == 1) {
                    let x = row.mergeCol === 0 ? 0 : row.mergeCol;
                    let y = row.mergeCol === 0 ? 0 : 1;
                    return [x, y];
                } else {
                    return [1.1];
                }
            },
            toImportStandard(){
                this.sheetInfos = [];
                this.loading = false;
                this.buttonLoading = false;
                this.showFileImportModal = true;
            },
            async importFileByTemplate(e) {
                this.sheetInfos = [];
                this.loading = true;
                var vali = /\.(xls|xlsx)$/;
                if (!vali.test(e.name.toLowerCase())) {
                    this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
                    return false;
                }
                const index = e.name.lastIndexOf(".");
                var fileName = e.name.substring(0, index)
                const fileReader = new FileReader();
                let this_ = this;
                fileReader.onload = async function (e1) {
                    try {
                        const data1 = e1.target.result; // data则是我们在excel表中获取的数据
                        var XLSX = require("xlsx");
                        const Workbook = XLSX.read(data1, {type: 'binary'}); // 通过XLSX读取出来得到了一个 workdata 对象，下面详细介绍 workdata 对象中有些什么
                        var title = {
                            title: fileName,
                            orgId: this_.userInfo.companyId,
                            children:[]
                        }
                        var array1 = [];
                        var array2 = [];
                        var array1Index = this_.codingList1.length + 1;
                        var array2Index = this_.codingList2.length + 1;
                        var sheetLength = Workbook.SheetNames.length;
                        for(var sheetIndex = 1;sheetIndex < sheetLength;sheetIndex++) {
                            var sheetName = {
                                title: Workbook.SheetNames[sheetIndex],
                                orgId: this_.userInfo.companyId,
                                children:[]
                            }
                            let workSheet = Workbook.Sheets[Workbook.SheetNames[sheetIndex]]
                            const execlDatas = XLSX.utils.sheet_to_json(workSheet);
                            var standardDataByTemplate = [];
                            for (var i = 3; i < execlDatas.length; i++) {
                                var execlData = execlDatas[i];
                                var obj = {
                                    managementElementsName:execlData["__EMPTY"],
                                    pollutionFactorName:execlData["__EMPTY_2"],
                                    legalResponsibility: execlData["__EMPTY_4"],
                                    lawsRegulations: execlData["__EMPTY_5"],
                                    riskLevelName: execlData["__EMPTY_6"],
                                    orgId: this_.userInfo.companyId,
                                    enabled: "1"
                                }
                                if(obj.managementElementsName == undefined && sheetName.children.length > 0){
                                    obj.managementElementsName = sheetName.children[sheetName.children.length-1].managementElementsName;
                                }
                                obj.managementElements = this_.managementElementsMap[obj.managementElementsName];
                                if(obj.managementElements == undefined && obj.managementElementsName != undefined){
                                    array1.push({index:array1Index,
                                      codingName:obj.managementElementsName});
                                    this_.managementElementsMap[obj.managementElementsName] = "eco-000010000000" + array1Index;
                                    obj.managementElements = "eco-000010000000" + array1Index;
                                    array1Index++;
                                }
                                obj.pollutionFactor = this_.pollutionFactorMap[obj.pollutionFactorName];
                                if(obj.pollutionFactor == undefined && obj.pollutionFactorName != undefined){
                                  array2.push({index:array2Index,
                                    codingName:obj.pollutionFactorName});
                                  this_.pollutionFactorMap[obj.pollutionFactorName] = "eco-000020000000" + array2Index;
                                  obj.pollutionFactor = "eco-000020000000" + array2Index;
                                  array2Index++;
                                }
                                obj.riskLevel = this_.riskLevelMap[obj.riskLevelName];
                                standardDataByTemplate.push(obj);
                                sheetName.children.push(obj);
                            }
                            sheetName.children = this_.formatData(sheetName.children);
                            this_.sheetInfos.push({sheetName:Workbook.SheetNames[sheetIndex],
                                standardDataByTemplate:standardDataByTemplate});
                            title.children.push(sheetName);
                        }
                        if(this_.sheetInfos.length >0)
                            this_.currentSheet = this_.sheetInfos[0].sheetName;
                        else
                            this_.currentSheet="";
                        this_.standardDatasByTemplate = title;
                      for(var i = 0;i<array1.length;i++){
                        var item = array1[i];
                        var sortData = {
                          codingCodeId: "eco-000010000000" + item.index,
                          codingSortId: "eco-00001",
                          codingCode: "00" + item.index,
                          codingName: item.codingName
                        }
                        await this_.$http.post(Api.addCodeDetail, sortData).then(res => {

                        }).catch(e => {
                          this_.$Message.error('请求失败');
                        })
                      }
                      for(var i = 0;i<array2.length;i++){
                            var item = array2[i];
                            var sortData = {
                                codingCodeId: "eco-000020000000" + item.index,
                                codingSortId: "eco-00002",
                                codingCode: "00" + item.index,
                                codingName: item.codingName
                            }
                            await this_.$http.post(Api.addCodeDetail, sortData).then(res => {
                            }).catch(e => {
                                this_.$Message.error('请求失败');
                            })
                        }
                        this_.loading = false;
                    } catch (e) {
                        console.log(e)
                        return false;
                    }
                };
                fileReader.readAsBinaryString(e);
                return false;
            },
            formatData(data) {
                let names = [];
                //筛选出不重复的 name值,将其放到 names数组中
                data.forEach((e) => {
                    if (!names.includes(e.managementElementsName)) {
                        names.push(e.managementElementsName);
                    }
                });
                let nameNums = [];
                //将names数组中的 name值设置默认合并0个单元格,放到 nameNums中
                names.forEach((e) => {
                    nameNums.push({ managementElementsName: e, num: 0 });
                });
                //计算每种 name值所在行需要合并的单元格数
                data.forEach((e) => {
                    nameNums.forEach((n) => {
                        if (e.managementElementsName === n.managementElementsName) {
                            n.num++;
                        }
                    });
                });
                //将计算后的合并单元格数整合到 data中
                data.forEach((e) => {
                    nameNums.forEach((n) => {
                        if (e.managementElementsName === n.managementElementsName) {
                            if (names.includes(e.managementElementsName)) {
                                e.mergeCol = n.num;
                                //删除已经设置过的值(防止被合并的单元格进到这个 if 语句中)
                                names.splice(names.indexOf(n.managementElementsName), 1);
                            } else {
                                //被合并的单元格设置为 0
                                e.mergeCol = 0;
                            }
                        }
                    });
                });
                //将整理后的数据交给表格渲染
                return data;
            },
        },
    }
</script>

<style scoped>
    @import './../../../index.css';
    .demo-split{
        height: 200px;
        border: 1px solid #dcdee2;
    }
    .demo-split-pane{
        padding: 10px;
    }
</style>
